package com.yxh.sse.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class RandomAction {

	private static final long serialVersionUID = -2269414914034390741L;
	private Random random;
	private BufferedImage image;
	private Font font;
	private int distance;

	public String getCheckCodeImage(String str, int show, OutputStream output)
			throws IOException {
		random = new Random();
		image = new BufferedImage(70, 25, BufferedImage.TYPE_3BYTE_BGR);
		font = new Font("Arial", Font.PLAIN, 20);
		this.distance = 15;
		Graphics d = image.getGraphics();
		d.setColor(Color.WHITE);
		d.fillRect(0, 0, image.getWidth(), image.getHeight());
		d.setColor(new Color(random.nextInt(100) + 100,
				random.nextInt(100) + 100, random.nextInt(100) + 100));
		for (int i = 0; i < 10; i++) {
			d.drawLine(random.nextInt(image.getWidth()), random.nextInt(image
					.getHeight()), random.nextInt(image.getWidth()), random
					.nextInt(image.getHeight()));
		}
		d.setColor(Color.BLACK);
		d.setFont(font);
		String checkCode = "";
		char tmp = 0;
		int x = -distance;
		for (int i = 0; i < show; i++) {
			tmp = str.charAt(random.nextInt(str.length() - 1));
			checkCode = checkCode + tmp;
			x = x + distance;
			d.setColor(new Color(random.nextInt(100) + 50,
					random.nextInt(100) + 50, random.nextInt(100) + 50));
			d.drawString(tmp + "", x, random.nextInt(image.getHeight()
					- (font.getSize()))
					+ (font.getSize()));
		}
		d.dispose();
		ImageIO.write(image, "jpeg", output);
		return checkCode;
	}

	public String execute() throws Exception {

		HttpServletResponse response = ServletActionContext.getResponse();
		ActionContext.getContext().getSession().put(
				"random",
				this.getCheckCodeImage("ABCDEFGHJKLMNPQRSTUVWXYZ123456789", 4,
						response.getOutputStream()));

		return "success";
	}

}
